package com.lie.prepare.multi_thread.pipe;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.lie.prepare.util.Print.*;
/**
 * Created by lie on 2018/4/10.
 *  以管道形式对线程输入输出提供了支持
 *  在出现{@link java.util.concurrent.BlockingQueue}之前，是一个常见的形式
 */
public class PipedIO {
    public static void main(String[] args) throws IOException, InterruptedException {
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);

        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(sender);
        exec.execute(receiver);
        TimeUnit.SECONDS.sleep(4);
        exec.shutdownNow();
    }
}


class Sender implements Runnable{

    private Random random = new Random(47);
    private PipedWriter out = new PipedWriter();

    public PipedWriter getPipedWriter() {
        return out;
    }

    public void run() {
        try {
            for (char i='A';i<='Z';i++){
                out.write(i);
                TimeUnit.MILLISECONDS.sleep(random.nextInt(500));
            }
        } catch (IOException e) {
            print("Sender 输出 异常");
        } catch (InterruptedException e) {
            print("sender sleep InterruptedException");
        }
    }
}

class Receiver implements Runnable{
    private PipedReader in;

    public Receiver(Sender sender) throws IOException {
        in = new PipedReader(sender.getPipedWriter());
    }

    public void run() {
        try {
            while (true) {
                print("receiver: "+  (char)in.read()+ ",");
            }
        } catch (IOException e) {
            print("Receiver read ioException");
        }
    }
}